package com.rockcent.mall.controller;

import com.aliyun.oss.OSSClient;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.mall.Prop;
import com.rockcent.mall.Routes;
import com.rockcent.mall.helper.UserHelper;
import com.rockcent.mall.lib.domain.UploadImageFile;
import com.rockcent.mall.lib.domain.enumclass.UploadFileBusinessType;
import com.rockcent.mall.lib.dto.UploadImageFileDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.QRCodeHelper;
import com.rockcent.mall.lib.repository.MallRepository;
import com.rockcent.mall.lib.repository.MerchantRepository;
import com.rockcent.mall.lib.repository.UploadImageFileRepository;
import org.apache.commons.lang3.EnumUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by HK on 16/9/25.
 */
@RestController
public class UploadController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private OSSClient ossClient;
    @Autowired
    private UploadImageFileRepository uploadImageFileRepository;
    @Autowired
    private Prop prop;
    @Autowired
    private UserHelper userHelper;

    @Autowired
    private MallRepository mallRepository;

    @Autowired
    private MerchantRepository merchantRepository;

    @Autowired
    private QRCodeHelper qrCodeHelper;


    /**
     * @api {post} /upload/image 上传图片(单个)
     * @apiGroup upload
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {File} file <code>必须参数</code>文件
     * @apiParam {String=PRODUCT_FACE("/product/face","产品封面图"), MERCHANT_WECHAT_CERTIFICATE("/merchant/wechat/certificate","商户微信证书"),USER_FEEDBACK("/user/feedback","用户反馈图片")} businessType <code>必须参数</code> 业务类型
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *       "id":1,
     *       "path":"http://uploads.rockcent.com/dev/product/face/20169/251546123108b958281-b920-49de-b57b-5433cb0c2401u=3845662385,2620759967&fm=58.jpeg"
     *  }
     * }
     */
    @RequestMapping(value = "/upload/image", method = RequestMethod.POST)
    public JsonResult uploadFile(MultipartFile file, String businessType, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing restDoing = jsonResult -> {
            if (file == null) {
                jsonResult.errorParam("file 不能为空",log);
                return;
            }

            // 当图片大于2M 不允许上传
            if (file.getSize() > 1024 * 1024 * 2) {
                jsonResult.errorParam("上传图片不能超过2M",log);
                return;
            }


            if (businessType == null) {
                jsonResult.errorParam("businessType 不能为空",log);
                return;
            }

            if (!EnumUtils.isValidEnum(UploadFileBusinessType.class, businessType)) {
                jsonResult.remind("业务类型 只允许 PRODUCT_FACE(\"/product/face\",\"产品封面图\"),MERCHANT_WECHAT_CERTIFICATE(\"/merchant/wechat/certificate\",\"商户微信证书\")",log);
                return;
            }
            UploadImageFileDto uploadImageFileDto = this.doUpload(file, businessType, userInfoDto);
            jsonResult.data = uploadImageFileDto;
        };
        return restDoing.go(request, log);
    }

    /**
     *
     * @api {post} /upload/image_simditor 上传图片(单个) tower编辑器图片
     * @apiGroup upload
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {File} file <code>必须参数</code>文件
     * @apiParam {String=PRODUCT_FACE("/product/face","产品封面图")} businessType <code>必须参数</code> 业务类型
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "success": "1",
     *  "msg": "成功",
     *  "file_path": "http://uploads.rockcent.com/dev/product/face/20169/251546123108b958281-b920-49de-b57b-5433cb0c2401u=3845662385,2620759967&fm=58.jpeg"
     * }
     */
    @RequestMapping(value = "/upload/image_simditor", method = RequestMethod.POST)
    public Map<String, Object> imageSimditor(MultipartFile file, String businessType, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        Map<String, Object> data = new HashMap();
        if (file == null) {
            data.put("success", false);
            data.put("msg", "file 不能为空");
            return data;
        }

        // 当图片大于2M 不允许上传
        if (file.getSize() > 1024 * 1024 * 2) {
            data.put("success", false);
            data.put("msg", "上传图片不能超过2M");
            return data;
        }

        if (businessType == null) {
            data.put("success", false);
            data.put("msg", "businessType 不能为空");
            return data;
        }

        if (!EnumUtils.isValidEnum(UploadFileBusinessType.class, businessType)) {
            data.put("success", false);
            data.put("msg", "业务类型 只允许 PRODUCT_FACE(\"/product/face\",\"产品封面图\")");
            return data;
        }
        UploadImageFileDto uploadImageFileDto = null;
        try {
            uploadImageFileDto = this.doUpload(file, businessType, userInfoDto);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        data.put("success", true);
        data.put("msg", "success");
        data.put("file_path", uploadImageFileDto.getPath());
        return data;
    }

    private UploadImageFileDto doUpload(MultipartFile file, String businessType, UserInfoDto userInfoDto) throws IOException {
        UploadImageFile uploadImageFile = new UploadImageFile();
        // 文件名
        String fileName = uploadImageFile.genFileName(file.getOriginalFilename());
        String allPath = uploadImageFile.genAllPath(prop.env, UploadFileBusinessType.valueOf(businessType), fileName);

        log.info("======================>userInfoDto merchant:{}",userInfoDto.merchant);
        if(userInfoDto.merchant!=null) {
            log.info("======================>userInfoDto merchantId:{}",userInfoDto.merchant.getId());
        }
        log.info("======================>userInfoDto mall:{}",userInfoDto.mall);
        if(userInfoDto.mall!=null) {
            log.info("======================>userInfoDto mallId:{}",userInfoDto.mall.getId());
        }

        uploadImageFile.setSize(file.getSize());
        uploadImageFile.setOriginFileName(file.getOriginalFilename());
        uploadImageFile.setFileName(fileName.toString());
        uploadImageFile.setPath("/" + allPath);
        uploadImageFile.setBusinessType(UploadFileBusinessType.valueOf(businessType));
        uploadImageFile.setUserInfoId(userInfoDto.getId());
        //商户ID不存在不保存
        if(userInfoDto.merchant != null && userInfoDto.merchant.getId()!=null) {
            uploadImageFile.setMerchantId(userInfoDto.merchant.getId());
        }
        uploadImageFile.setMallId(userInfoDto.mall.getId());
        uploadImageFile = uploadImageFileRepository.save(uploadImageFile);

        ossClient.putObject(prop.aliyunOssBucketName, allPath, file.getInputStream());

        UploadImageFileDto uploadImageFileDto = new UploadImageFileDto();
        uploadImageFileDto.setPath(prop.domainUploadsHttp + "/" + uploadImageFile.getPath());
        uploadImageFileDto.setId(uploadImageFile.getId());
        return uploadImageFileDto;
    }

    /**
     *
     * @api {get}  /qrcode/download  公共 二维码下载
     * @apiGroup upload
     * @apiVersion 1.0.0
     * @apiHeader  {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} url    下载资源URL
     * @apiParam {String} source    来源，WXAPP:微信小程序；WEXIN:公众号H5
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": FFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH/"
     * }
     * */
    @RequestMapping(value = Routes.QRCODE_DOWNLOAD, method = RequestMethod.GET)
    public JsonResult downloadQRCode(String url, String source, HttpServletRequest request, HttpServletResponse response) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (url == null) {
                jsonResult.remind("资源URL不能为空",log);
                return;
            }

            //http://uploads.rockcent.com/dev/gift_packet/promote/201611/29154530925b2a6249d-67f2-4757-9b7f-9e135bef8e11giftPacketPromote.jpg
            String downloadUrl;// qrCodeHelper.createBase64QRCode(url);
            if("WXAPP".equals(source)){
                downloadUrl =qrCodeHelper.createBase64QRCodeWxapp(url);
            }else{
                downloadUrl = qrCodeHelper.createBase64QRCode(url);
            }
            jsonResult.data = downloadUrl;
        };

        return doing.go(request, log);
    }
}
